# encoding: utf-8
# @project: st2111 
# @file: re_test_patterns_groups.py
# @time: 2023/4/13 15:11
# @author: abcque
# @license: (C) Copyright 2013-2021
# @contact: abcque@outlook.com
# @IDE: PyCharm
# @desc:
import re


def test_patterns(text, patterns):
    """
    :param text: 要使用正则匹配的字符
    :param patterns: 正则表达式和表达式解释元祖组成的列表
    :return: 无
    """
    for pattern, desc in patterns:
        print('{!r} ({})\n'.format(pattern, desc))
        print('  {!r}'.format(text))
        for match in re.finditer(pattern, text):
            s = match.start()
            e = match.end()
            prefix = ' ' * (s)
            # 输出正则表达式匹配的字符串，以空格结尾不换号
            print('  {}{!r}{} '.format(prefix, text[s:e], ' ' * (len(text) - e)), end=' ', )
            # 输出组的结果， 最外层的组匹配结果或者第一个匹配结果，第二个匹配结果...
            print(match.groups())
            if match.groupdict():
                print('{}{}'.format(' ' * (len(text) - s), match.groupdict()), )
        print()
    return


if __name__ == "__main__":
    text = 'abbaabbba'
    patterns = [
        (r'a((a*)(b*))', 'a followed by 0-n a and 0-n b'),
        (r'a((?P<serial_A>a*)(?P<serial_B>a*b*))', 'a followed by 0-n a and 0-n b'),

    ]
    test_patterns(text=text, patterns=patterns)
